package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.service.AdChannelService;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.aliyun.GreenTextScan;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsVo;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    AdChannelService adChannelService;

    @Autowired
    GreenTextScan greenTextScan;

    @Autowired
    GreenImageScan greenImageScan;

    @Autowired
    FastDFSClient fastDFSClient;

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    AdSensitiveService adSensitiveService;


    @GlobalTransactional
    public void autoScanNewsId(Integer id) {
        //参数校检
        if (id == null) {
            return;
        }
        WmNews wmNews = wemediaFeign.findByNewsId(id);
        if (wmNews == null) {
            return;
        }

        //根据文章状态决定是否审核
        if (wmNews.getStatus() == 4) {
            //人工审核通过
            this.saveArticle(wmNews);
        }

        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            this.saveArticle(wmNews);
        }

        //审核阿里云内容安全接口敏感词
        if (wmNews.getStatus() == 1) {
            //审核文本 --阿里云
            Map<String, Object> map = this.handTextAndImageScan(wmNews);
            String textStr = (String) map.get("content");
            boolean textScan = this.handTextScan(textStr, wmNews);
            if (!textScan) {
                return;
            }

            //审核阿里云图片安全接口
            List<String> imageList =(List<String>) map.get("images");
            boolean imageScan = this.handImageScan(imageList, wmNews);
            if (!imageScan){
                return;
            }

            //审核自定义敏感词
            Boolean handSensitive = this.handSensitive(textStr, wmNews);
            if (!handSensitive){
                return;
            }



        }


        //批量保存
        this.saveArticle(wmNews);

//        wmNews.setArticleId();
        //修改wmnews status字段  8/9
        if (wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
            this.updateWmNewsStatus(wmNews,(short)8,"审核通过，待发布");
        }else {
            this.updateWmNewsStatus(wmNews,(short)9,"审核通过，已发布");

        }

    }


    //审核自定义敏感词
    private Boolean handSensitive(String content,WmNews wmNews){
        boolean flag =false;
        List<AdSensitive> senesitiveList = adSensitiveService.findAll();
        List<String> listStr = new ArrayList<>();
        for (AdSensitive adSensitive : senesitiveList) {
            listStr.add(adSensitive.getSensitives());
        }
        SensitiveWordUtil.initMap(listStr);

        Map<String, Integer> words = SensitiveWordUtil.matchWords(content);
        if (words.size()==0){
            //包含敏感词，审核通过
            flag=true;
        }else {
            //不通过
            this.updateWmNewsStatus(wmNews,(short) 2,"内容中包含敏感词");
        }

        return flag;
    }

    //审核文本 --阿里云
    private Map<String,Object> handTextAndImageScan(WmNews wmNews){
        String content = wmNews.getContent();
        StringBuilder stringBuilder = new StringBuilder();
        ArrayList<String> imageList = new ArrayList<>();

        List<Map> list = JSON.parseArray(content, Map.class);
        for (Map map : list) {
            if (map.get("type").equals("text")){
                stringBuilder.append(map.get("value"));
            }
            if (map.get("type").equals("image")){
                imageList.add(map.get("value").toString());
            }
        }

        //分离封面图片
        if (wmNews.getImages()!=null && wmNews.getType()>0){
            String[] strings = wmNews.getImages().split(",");
            imageList.addAll(Arrays.asList(strings));
        }

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",imageList);
        return resultMap;
    }

    //审核阿里云图片安全接口
    private boolean handImageScan(List<String> images, WmNews wmNews) {
        if (images == null) {
            return true;
        }
        boolean flag = false;

        try {
            ArrayList<byte[]> imagesList = new ArrayList<>();
            for (String image : images) {
                //替换  http://192.168.58.138/
                String replace = image.replace(fileServerUrl, "");
                String groupName = replace.substring(0, replace.indexOf("/"));
                String groupPath = replace.substring(replace.indexOf("/") + 1);
                byte[] download = fastDFSClient.download(groupName, groupPath);
                imagesList.add(download);
            }

            Map map = greenImageScan.imageScan(imagesList);
            if (!map.get("suggestion").equals("pass")) {
                if (map.get("suggestion").equals("block")) {
                    this.updateWmNewsStatus(wmNews, (short) 2, "图片审核不通过");
                }
                if (map.get("suggestion").equals("review")) {
                    this.updateWmNewsStatus(wmNews, (short) 3, "图片审核不确定,建议人工审核");
                }
            } else {
                flag = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    //审核阿里云内容安全接口敏感词
    private boolean handTextScan(String content, WmNews wmNews) {
        boolean flag = false;
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (!map.get("suggestion").equals("pass")) {
                if (map.get("suggestion").equals("block")) {
                    this.updateWmNewsStatus(wmNews, (short) 2, "文本审核不通过");
                }
                if (map.get("suggestion").equals("review")) {
                    this.updateWmNewsStatus(wmNews, (short) 3, "文本审核不确定,建议人工审核");
                }
            } else {
                flag = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    private void updateWmNewsStatus(WmNews wmNews, short Status, String msg) {
        wmNews.setStatus(Status);
        wmNews.setReason(msg);
        wemediaFeign.updateByStatus(wmNews);
    }

    //保存数据   ap_article  ap_article_content    ap_article_config
    private void saveArticle(WmNews wmNews) {
        //ap_article
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());

        //查询用户
        Integer userId = wmNews.getUserId();
        ApAuthor apAuthor = articleFeign.findByWmUserId(userId);
        if (apAuthor != null) {
            apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
            apArticle.setAuthorName(apAuthor.getName());
        }

        //查询频道
        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelService.getById(channelId);
        if (adChannel != null) {
            apArticle.setChannelId(channelId);
            apArticle.setChannelName(adChannel.getName());
        }
        ApArticle apArticle1 = articleFeign.saveArticle(apArticle);

        //ap_article_content
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        ApArticleContent apArticleContent1 = articleFeign.saveArticleContent(apArticleContent);

        //ap_article_config
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle1.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);

        ApArticleConfig apArticleConfig1 = articleFeign.saveArticleConfig(apArticleConfig);

    }





    @Override
    public ResponseResult findNews(NewsAuthDto dto) {
        ResponseResult list = wemediaFeign.findList(dto);
        list.setHost(fileServerUrl);
        return list;
    }

    @Override
    public ResponseResult findNewsById(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        return ResponseResult.okResult(wmNewsVo);
    }



    @Override
    public ResponseResult authPass(NewsAuthDto dto) {
        if (dto==null && dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmNews wmNews = wemediaFeign.findByNewsId(dto.getId());
        this.updateWmNewsStatus(wmNews,(short)4,"人工审核通过");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult authFail(NewsAuthDto dto) {
        if (dto==null && dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmNews wmNews = wemediaFeign.findByNewsId(dto.getId());
        this.updateWmNewsStatus(wmNews,(short)2,"人工审核通过");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
